<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">我的通知</text>
			<view class="action-buttons">
				<button class="action-btn secondary" @click="toggleBatchMode" v-if="notifications.length > 0">
					{{batchMode ? '取消' : '选择'}}
				</button>
				<button class="action-btn" @click="markAllAsRead" v-if="unreadCount > 0 && !batchMode">全部已读</button>
			</view>
		</view>
		
		<!-- 批量操作栏 -->
		<view class="batch-toolbar" v-if="batchMode">
			<view class="batch-left">
				<checkbox-group @change="toggleSelectAll">
					<label class="select-all-item">
						<checkbox value="all" :checked="isAllSelected" />
						<text>全选({{selectedNotifications.length}}/{{notifications.length}})</text>
					</label>
				</checkbox-group>
			</view>
			<view class="batch-right">
				<button class="batch-btn danger" @click="batchDelete" :disabled="selectedNotifications.length === 0">
					删除({{selectedNotifications.length}})
				</button>
				<button class="batch-btn" @click="batchMarkAsRead" 
					:disabled="selectedNotifications.length === 0 || !hasUnreadSelected">
					标为已读
				</button>
			</view>
		</view>
		
		<!-- 分类选择 -->
		<view class="category-section">
			<scroll-view scroll-x class="category-scroll" show-scrollbar="false">
				<view class="category-list">
					<view 
						class="category-item" 
						:class="{'active': currentCategory === 'all'}"
						@click="switchCategory('all')"
					>
						全部<text class="count" v-if="totalCount > 0">({{totalCount}})</text>
					</view>
					<view 
						class="category-item" 
						:class="{'active': currentCategory === 'unread'}"
						@click="switchCategory('unread')"
					>
						未读<text class="count" v-if="unreadCount > 0">({{unreadCount}})</text>
					</view>
					<view 
						class="category-item" 
						:class="{'active': currentCategory === 'read'}"
						@click="switchCategory('read')"
					>
						已读<text class="count" v-if="readCount > 0">({{readCount}})</text>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 通知列表 -->
		<view class="notification-list">
			<view v-if="loading" class="loading-box">
				<uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
			</view>
			<block v-else>
				<view 
					class="notification-item" 
					:class="{'unread': !item.is_read, 'batch-mode': batchMode, 'selected': selectedNotifications.includes(item._id)}"
					v-for="(item, index) in notifications" 
					:key="index"
					@click="batchMode ? toggleSelect(item._id) : navigateToDetail(item._id, item)"
				>
					<!-- 批量模式复选框 -->
					<view class="checkbox-wrapper" v-if="batchMode" @click.stop="toggleSelect(item._id)">
						<checkbox :checked="selectedNotifications.includes(item._id)" />
					</view>
					
					<view class="notification-content">
						<view class="notification-title">
							<text class="title-text">{{item.title}}</text>
							<view class="unread-dot" v-if="!item.is_read"></view>
						</view>
						<view class="notification-summary">{{item.content}}</view>
						<view class="notification-info">
							<text class="notification-category">{{item.category}}</text>
							<text class="notification-date">{{formatDate(item.create_time)}}</text>
						</view>
					</view>
					
					<view class="notification-actions" v-if="!batchMode">
						<button class="delete-btn" @click.stop="deleteNotification(item._id)">删除</button>
					</view>
				</view>
				
				<!-- 无数据提示 -->
				<view v-if="notifications.length === 0" class="empty-box">
					<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无通知</text>
				</view>
				
				<!-- 加载更多 -->
				<uni-load-more v-if="notifications.length > 0" :status="loadMoreStatus" :content-text="loadingText" @clickLoadMore="loadMore"></uni-load-more>
			</block>
		</view>
	</view>
</template>

<script>
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				loading: true,
				notifications: [],
				currentCategory: 'all', // all, read, unread
				page: 1,
				limit: 10,
				totalCount: 0,
				unreadCount: 0,
				readCount: 0,
				loadMoreStatus: 'more',
				loadingText: {
					contentdown: '上拉加载更多',
					contentrefresh: '加载中...',
					contentnomore: '没有更多数据了'
				},
				userInfo: {},
				// 批量操作相关
				batchMode: false,
				selectedNotifications: []
			}
		},
		computed: {
			// 是否全选
			isAllSelected() {
				return this.notifications.length > 0 && this.selectedNotifications.length === this.notifications.length;
			},
			// 选中的通知中是否有未读的
			hasUnreadSelected() {
				return this.selectedNotifications.some(id => {
					const notification = this.notifications.find(item => item._id === id);
					return notification && !notification.is_read;
				});
			}
		},
		onLoad() {
			this.getUserInfo();
			this.getNotifications();
			this.getUnreadCount();
		},
		onShow() {
			// 页面显示时刷新未读数量
			this.getUnreadCount();
		},
		onPullDownRefresh() {
			this.refreshList();
		},
		onReachBottom() {
			this.loadMore();
		},
		methods: {
			// 获取用户信息
			getUserInfo() {
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						this.userInfo = JSON.parse(userInfoStr);
					} catch (e) {
						console.error('解析用户信息失败', e);
					}
				}
			},
			
			// 获取通知列表
			async getNotifications() {
				this.loading = true;
				
				try {
					const notificationService = uniCloud.importObject('notification-service');
					const res = await notificationService.getNotifications(
						this.userInfo._id,
						this.page,
						this.limit,
						this.currentCategory
					);
					
					if (res.code === 0) {
						if (this.page === 1) {
							this.notifications = res.data || [];
						} else {
							this.notifications = [...this.notifications, ...(res.data || [])];
						}
						
						this.totalCount = res.total || 0;
						
						// 判断是否还有更多数据
						if (this.notifications.length >= this.totalCount) {
							this.loadMoreStatus = 'noMore';
						} else {
							this.loadMoreStatus = 'more';
						}
					} else {
						uni.showToast({
							title: res.message || '获取通知列表失败',
							icon: 'none'
						});
					}
				} catch (err) {
					console.error('获取通知列表失败', err);
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},
			
			// 获取未读数量
			async getUnreadCount() {
				try {
					const notificationService = uniCloud.importObject('notification-service');
					const res = await notificationService.getUnreadCount(this.userInfo._id);
					
					if (res.code === 0) {
						this.unreadCount = res.data.unreadCount;
						this.readCount = this.totalCount - this.unreadCount;
					}
				} catch (err) {
					console.error('获取未读数量失败:', err);
				}
			},
			
			// 切换分类
			switchCategory(category) {
				if (this.currentCategory === category) return;
				
				this.currentCategory = category;
				this.page = 1;
				this.notifications = [];
				this.getNotifications();
			},
			
			// 加载更多
			loadMore() {
				if (this.loadMoreStatus === 'noMore' || this.loading) return;
				
				this.page++;
				this.getNotifications();
			},
			
			// 刷新列表
			refreshList() {
				this.page = 1;
				this.notifications = [];
				this.getNotifications();
				this.getUnreadCount();
			},
			
			// 跳转到详情页或相关页面
			navigateToDetail(notificationId, notification) {
				if (!notificationId) return;
				
				// 如果通知有额外数据且包含跳转链接，直接跳转到相关页面
				if (notification && notification.extra_data && notification.extra_data.jump_url) {
					// 先标记为已读
					this.markNotificationAsRead(notificationId);
					
					// 跳转到相关页面
					uni.navigateTo({
						url: notification.extra_data.jump_url
					});
					return;
				}
				
				// 如果是比赛相关通知，直接跳转到比赛详情
				if (notification && notification.type === 'match_publish' && notification.related_id) {
					// 先标记为已读
					this.markNotificationAsRead(notificationId);
					
					// 跳转到比赛详情
					uni.navigateTo({
						url: `/packgeCompetition/competition/detail?id=${notification.related_id}`
					});
					return;
				}
				
				// 如果是执裁评价通知，直接跳转到执裁记录详情
				if (notification && notification.type === 'referee_evaluation') {
					// 先标记为已读
					this.markNotificationAsRead(notificationId);
					
					// 跳转到执裁记录详情或列表
					if (notification.extra_data && notification.extra_data.record_id) {
						uni.navigateTo({
							url: `/packageMy/my/match-record-detail?id=${notification.extra_data.record_id}`
						});
					} else {
						uni.navigateTo({
							url: `/packageMy/my/match-records`
						});
					}
					return;
				}
				
				// 默认跳转到通知详情页
				uni.navigateTo({
					url: `/packageNotice/Notice/notification-detail?id=${notificationId}`
				});
			},
			
			// 标记单个通知为已读
			async markNotificationAsRead(notificationId) {
				try {
					const notificationService = uniCloud.importObject('notification-service');
					await notificationService.markAsRead(notificationId, this.userInfo._id);
					
					// 更新本地通知状态
					const notification = this.notifications.find(item => item._id === notificationId);
					if (notification && !notification.is_read) {
						notification.is_read = true;
						this.unreadCount = Math.max(0, this.unreadCount - 1);
					}
				} catch (err) {
					console.error('标记已读失败:', err);
					// 不显示错误提示，不影响用户体验
				}
			},
			
			// 全部标记为已读
			async markAllAsRead() {
				try {
					uni.showLoading({ title: '处理中...' });
					
					const notificationService = uniCloud.importObject('notification-service');
					const res = await notificationService.markAllAsRead(this.userInfo._id);
					
					uni.hideLoading();
					
					if (res.code === 0) {
						uni.showToast({
							title: '全部已读',
							icon: 'success'
						});
						
						// 刷新列表和计数
						this.refreshList();
					} else {
						uni.showToast({
							title: res.message || '操作失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.hideLoading();
					console.error('全部已读失败:', err);
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				}
			},
			
			// 删除通知
			async deleteNotification(id) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这条通知吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								
								const notificationService = uniCloud.importObject('notification-service');
								const result = await notificationService.deleteNotification(id, this.userInfo._id);
								
								uni.hideLoading();
								
								if (result.code === 0) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									
									// 从列表中移除已删除的通知
									this.notifications = this.notifications.filter(item => item._id !== id);
									this.totalCount--;
									this.getUnreadCount();
								} else {
									uni.showToast({
										title: result.message || '删除失败',
										icon: 'none'
									});
								}
							} catch (err) {
								uni.hideLoading();
								console.error('删除通知失败:', err);
								uni.showToast({
									title: '网络错误，请稍后再试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				
				const date = new Date(dateStr);
				const now = new Date();
				const diff = now.getTime() - date.getTime();
				
				// 计算时间差
				const minute = 1000 * 60;
				const hour = minute * 60;
				const day = hour * 24;
				
				if (diff < minute) {
					return '刚刚';
				} else if (diff < hour) {
					return Math.floor(diff / minute) + '分钟前';
				} else if (diff < day) {
					return Math.floor(diff / hour) + '小时前';
				} else if (diff < day * 2) {
					return '昨天';
				} else {
					const year = date.getFullYear();
					const month = (date.getMonth() + 1).toString().padStart(2, '0');
					const day = date.getDate().toString().padStart(2, '0');
					
					if (year === now.getFullYear()) {
						return `${month}-${day}`;
					} else {
						return `${year}-${month}-${day}`;
					}
				}
			},
			
			// ==================== 批量操作相关方法 ====================
			
			// 切换批量模式
			toggleBatchMode() {
				this.batchMode = !this.batchMode;
				if (!this.batchMode) {
					// 退出批量模式时清空选择
					this.selectedNotifications = [];
				}
			},
			
			// 切换选择某个通知
			toggleSelect(notificationId) {
				const index = this.selectedNotifications.indexOf(notificationId);
				if (index > -1) {
					this.selectedNotifications.splice(index, 1);
				} else {
					this.selectedNotifications.push(notificationId);
				}
			},
			
			// 全选/取消全选
			toggleSelectAll(e) {
				if (e.detail.value.includes('all')) {
					// 全选
					this.selectedNotifications = this.notifications.map(item => item._id);
				} else {
					// 取消全选
					this.selectedNotifications = [];
				}
			},
			
			// 批量删除
			async batchDelete() {
				if (this.selectedNotifications.length === 0) {
					uni.showToast({
						title: '请选择要删除的通知',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '批量删除',
					content: `确定要删除选中的${this.selectedNotifications.length}条通知吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								
								const notificationService = uniCloud.importObject('notification-service');
								const result = await notificationService.batchDeleteNotifications(
									this.selectedNotifications, 
									this.userInfo._id
								);
								
								uni.hideLoading();
								
								if (result.code === 0) {
									uni.showToast({
										title: result.message,
										icon: 'success'
									});
									
									// 从列表中移除已删除的通知
									this.notifications = this.notifications.filter(item => 
										!this.selectedNotifications.includes(item._id)
									);
									this.totalCount -= result.data.deletedCount;
									this.selectedNotifications = [];
									this.batchMode = false;
									this.getUnreadCount();
								} else {
									uni.showToast({
										title: result.message || '批量删除失败',
										icon: 'none'
									});
								}
							} catch (err) {
								uni.hideLoading();
								console.error('批量删除通知失败:', err);
								uni.showToast({
									title: '网络错误，请稍后再试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 批量标记为已读
			async batchMarkAsRead() {
				if (this.selectedNotifications.length === 0) {
					uni.showToast({
						title: '请选择要标记的通知',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({ title: '处理中...' });
					
					const notificationService = uniCloud.importObject('notification-service');
					const result = await notificationService.batchMarkAsRead(
						this.selectedNotifications, 
						this.userInfo._id
					);
					
					uni.hideLoading();
					
					if (result.code === 0) {
						uni.showToast({
							title: result.message,
							icon: 'success'
						});
						
						// 更新本地数据
						this.notifications.forEach(item => {
							if (this.selectedNotifications.includes(item._id)) {
								item.is_read = true;
								item.read_time = new Date();
							}
						});
						
						this.selectedNotifications = [];
						this.batchMode = false;
						this.getUnreadCount();
					} else {
						uni.showToast({
							title: result.message || '批量标记失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.hideLoading();
					console.error('批量标记已读失败:', err);
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style>
.container {
	padding-bottom: 30rpx;
	background-color: #F8F8F8;
	min-height: 100vh;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #F0F0F0;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
}

.action-btn {
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	background-color: #1BAE76;
	color: #FFFFFF;
	border-radius: 20rpx;
	border: none;
}

.action-btn.secondary {
	background-color: #666;
}

.category-section {
	padding: 20rpx 0;
	background-color: #fff;
	margin-bottom: 20rpx;
}

.category-scroll {
	white-space: nowrap;
}

.category-list {
	padding: 0 20rpx;
	display: flex;
}

.category-item {
	padding: 10rpx 30rpx;
	margin-right: 20rpx;
	font-size: 28rpx;
	color: #666;
	background-color: #f5f5f5;
	border-radius: 30rpx;
	white-space: nowrap;
}

.category-item.active {
	background-color: #1BAE76;
	color: #fff;
}

.count {
	font-size: 24rpx;
	margin-left: 5rpx;
}

.notification-list {
	padding: 0 20rpx;
}

.notification-item {
	display: flex;
	margin-bottom: 20rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	border-left: 4rpx solid transparent;
}

.notification-item.unread {
	border-left-color: #1BAE76;
	background-color: #FAFFFE;
}

.notification-item.batch-mode {
	cursor: pointer;
}

.notification-item.selected {
	background-color: #E8F5E8;
	border-left-color: #1BAE76;
}

.notification-content {
	flex: 1;
}

.notification-title {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

.unread-dot {
	width: 12rpx;
	height: 12rpx;
	background-color: #FF4757;
	border-radius: 6rpx;
	margin-left: 10rpx;
}

.notification-summary {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 15rpx;
	line-height: 1.5;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.notification-info {
	display: flex;
	align-items: center;
	font-size: 24rpx;
	color: #999;
}

.notification-category {
	padding: 4rpx 12rpx;
	background-color: #F0F0F0;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.notification-date {
	
}

.notification-actions {
	display: flex;
	flex-direction: column;
	justify-content: center;
	margin-left: 20rpx;
}

.delete-btn {
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	background-color: #FF4757;
	color: #FFFFFF;
	border-radius: 20rpx;
	border: none;
}

.empty-box {
	padding: 100rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.loading-box {
	padding: 30rpx 0;
}

/* 批量操作相关样式 */
.batch-toolbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #F0F0F0;
	margin-bottom: 20rpx;
}

.batch-left {
	flex: 1;
}

.select-all-item {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	color: #333;
}

.select-all-item checkbox {
	margin-right: 10rpx;
}

.batch-right {
	display: flex;
	gap: 20rpx;
}

.batch-btn {
	padding: 10rpx 20rpx;
	font-size: 24rpx;
	border-radius: 20rpx;
	border: none;
	background-color: #1BAE76;
	color: #FFFFFF;
}

.batch-btn.danger {
	background-color: #FF4757;
}

.batch-btn:disabled {
	background-color: #ccc;
	color: #999;
}

.checkbox-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 60rpx;
	height: 60rpx;
	margin-right: 20rpx;
}

.checkbox-wrapper checkbox {
	width: 32rpx;
	height: 32rpx;
}
</style> 